<?php
namespace app\service;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use think\facade\Config;
use think\facade\Log;

class MailService
{

    //composer require phpmailer/phpmailer
    /**
     * 发送邮件
     * @param string|array $to 收件人邮箱或数组[邮箱 => 姓名]
     * @param string $subject 邮件主题
     * @param string $body 邮件内容
     * @param bool $isHtml 是否为HTML格式
     * @return bool
     */
    public static function send($to, $subject, $body, $isHtml = true)
    {
        try {
            $config = Config::get('mail.smtp', []);

            if (empty($config)) {
                throw new \Exception('邮件配置未找到');
            }

            $mail = new PHPMailer(true);

            // 服务器配置
            $mail->isSMTP();
            $mail->Host       = $config['host'] ?? 'smtp.qq.com';
            $mail->SMTPAuth   = $config['auth'] ?? true;
            $mail->Username   = $config['username'] ?? '';
            $mail->Password   = $config['password'] ?? '';
            $mail->SMTPSecure = $config['secure'] ?? 'ssl';
            $mail->Port       = $config['port'] ?? 465;
            $mail->CharSet    = $config['charset'] ?? 'utf-8';

            // 调试模式（0=关闭, 1=客户端消息, 2=客户端和服务器消息）
            $mail->SMTPDebug = 0;

            // 发件人
            $from = $config['from'] ?? [];
            $mail->setFrom($from['address'] ?? $config['username'], $from['name'] ?? '');

            // 收件人
            if (is_array($to)) {
                foreach ($to as $email => $name) {
                    if (is_numeric($email)) {
                        $mail->addAddress($name);
                    } else {
                        $mail->addAddress($email, $name);
                    }
                }
            } else {
                $mail->addAddress($to);
            }

            // 邮件内容
            $mail->isHTML($isHtml);
            $mail->Subject = $subject;
            $mail->Body    = $body;

            if (!$isHtml) {
                $mail->AltBody = strip_tags($body);
            }

            // 发送邮件
            $result = $mail->send();

            if (!$result) {
                throw new \Exception('邮件发送失败: ' . $mail->ErrorInfo);
            }

            return true;

        } catch (Exception $e) {
            Log::error('邮件发送失败: ' . $e->getMessage());
            throw new \Exception('邮件发送失败: ' . $e->getMessage());
        }
    }

    /**
     * 发送HTML邮件
     */
    public static function sendHtml($to, $subject, $htmlBody)
    {
        return self::send($to, $subject, $htmlBody, true);
    }

    /**
     * 发送纯文本邮件
     */
    public static function sendText($to, $subject, $textBody)
    {
        return self::send($to, $subject, $textBody, false);
    }

    /**
     * 批量发送邮件
     */
    public static function batchSend($recipients, $subject, $body, $isHtml = true)
    {
        $results = [];
        foreach ($recipients as $recipient) {
            $results[$recipient] = self::send($recipient, $subject, $body, $isHtml);
        }
        return $results;
    }
}